import Vue from "vue";
import VueRouter from "vue-router";

import Login from "@/views/login.vue";
import Request from "@/views/register.vue";
import My from "@/views/my.vue";
import News from "@/views/news.vue";
import Lookup from "@/views/lookup.vue";
import Index from "@/views/index.vue";
import Footer from "@/views/footer.vue";
import Location from "@/views/location.vue";
import Collection from "@/views/collection.vue";
import Lease from "@/views/lease.vue";
import { Toast } from "vant";
Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/register",
    component: Request,
  },
  {
    path: "/location",
    component: Location,
  },
  {
    path: "/collection",
    component: Collection,
  },
  {
    path: "/lease",
    component: Lease,
  },
  {
    path: "/",
    component: Footer,
    redirect: "/index",
    children: [
      { path: "/my", component: My },
      { path: "/news", component: News },
      { path: "/lookup", component: Lookup },
      { path: "/index", component: Index },
    ],
  },
];
const whiteList = ["/login", "/register", "/my", "/news", "/lookup", "/index"];
const router = new VueRouter({
  routes,
});
router.beforeEach((to, form, next) => {
  if (localStorage.getItem("token")) {
    next();
  } else {
    // 没有token的人, 看看你要去哪
    // (1) 访问的是无需授权的页面（白名单），也是放行
    //     就是判断，访问的地址，是否在白名单数组中存在 includes
    if (whiteList.includes(to.path)) {
      next();
    } else {
      // (2) 否则拦截到登录
      next("/login");
      Toast.fail("你被拦截了");
    }
  }
});
export default router;
